# coding:utf-8
from bs4 import BeautifulSoup
import urllib.parse
import urllib.request
import string


def run():
    city_mapping = {
        '北京': '530',
        '上海': '538',
        '广州': '763',
        '深圳': '765',
        '天津': '531',
        '武汉': '736',
        '西安': '854',
        '成都': '801',
        '沈阳': '599',
        '南京': '635',
        '杭州': '653',
        '苏州': '639',
        '重庆': '551',
        '长沙': '749',
        '厦门': '682',
        '南昌': '691'
    }
    city_input = input("请输入城市：")
    jName = city_mapping.get(city_input, '530')  # 默认北京
    aName = input("请输入岗位：")

    # 构造URL
    url = f'https://sou.zhaopin.com/?jl={jName}&kw={aName}&p=1'
    url = urllib.parse.quote(url, safe=string.printable)

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
    }
    req = urllib.request.Request(url, headers=headers)
    try:
        res = urllib.request.urlopen(req)
        content = res.read().decode()
    except Exception as e:
        print(f"请求失败：{e}")
        return

    soup = BeautifulSoup(content, 'lxml')
    jobList = soup.select(".joblist-box__item")
    if not jobList:
        print("未找到职位信息，可能页面结构变化或未获取到数据。")
        return

    job_list = []
    for job in jobList:
        job_dic = {}
        try:
            # 岗位名称
            job_dic['job_name'] = job.select('.jobinfo__name')[0].get_text(strip=True)
            # 公司名称
            job_dic['company_name'] = job.select('.companyinfo__name')[0].get_text(strip=True)
            # 处理薪资
            salary_text = job.select('.jobinfo__salary')[0].get_text(strip=True)
            if '天' in salary_text:
                daily = int(salary_text.split('-')[0].replace('元/天', ''))
                job_dic['job_salary'] = daily * 30
            elif '千' in salary_text:
                min_k = int(salary_text.split('千')[0])
                job_dic['job_salary'] = min_k * 1000
            elif '万' in salary_text:
                # 处理范围值，取最小值部分转换
                min_w_part = salary_text.split('万')[0].split('-')[0]
                min_w = float(min_w_part)
                job_dic['job_salary'] = int(min_w * 10000)
            else:
                job_dic['job_salary'] = 5000
            # 处理地点、经验、学历
            info_items = job.select('.jobinfo__other-info-item')
            job_dic['job_loc'] = info_items[0].get_text(strip=True).split('-')[0] if len(info_items) > 0 else '未知'
            job_dic['job_exp'] = info_items[1].get_text(strip=True) if len(info_items) > 1 else '不限'
            job_dic['job_edu'] = info_items[2].get_text(strip=True) if len(info_items) > 2 else '不限'

            job_list.append(job_dic)
            print("爬取到职位:", job_dic)
        except Exception as e:
            print(f"解析职位信息失败：{e}")

    # 此处可添加数据库存储逻辑（若需要）
    # 示例打印结果
    for job in job_list:
        print(job)


if __name__ == "__main__":
    run()